<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>NoteLite</title>
  <style>
    body {
      background-color: #f5f5f5;
      font-size: 16px;
      font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
      color: #333;
      margin: 12px
    }
    #editor {
      width: 100%;
      height: calc(100vh - 24px);
      outline: none;
    }
    #hint {
      position: fixed;
      width: 10px;
      height: 10px;
      border-radius: 5px;
      background-color: rgba(4, 193, 23, 0.6);
      top: 5px;
      right: 5px;
      display: none;
    }
    img {
      max-width: 100%;
    }

    @media screen and (prefers-color-scheme: dark) {
      body {
        background-color: #202124;
        color: #fff;
      }
    }

  </style>
</head>
<body>
  <div id="editor" contenteditable="true"></div>
  <span id="hint"></span>
  <script>
    function save() {
      return new Promise((resolve, reject) => {
        const editor = document.getElementById('editor');
        const text = editor.innerHTML;
        if (text === '') {
          localStorage.removeItem('text');
        } else {
          localStorage.setItem('text', text);
        }
        resolve();
      });
    }
    function load() {
      const text = localStorage.getItem('text');
      if (text) {
        const editor = document.getElementById('editor');
        editor.innerHTML = text;
      }
    }

    let throttleTimeout;
    function onInput() {
      document.querySelector("#hint").style.display = 'inline-block';
      if (throttleTimeout) {
        clearTimeout(throttleTimeout);
      }
      throttleTimeout = setTimeout(() => {
        save().then(() => {
          document.querySelector("#hint").style.display = 'none';
        });
      }, 800);
    }

    document.querySelector("#editor").addEventListener("input", function() {
      onInput();
    }, false);

    document.addEventListener('paste', function(event) {
      const items = (event.clipboardData && event.clipboardData.items) || [];
      if (items && items.length) {
        for (let i = 0; i < items.length; i++) {
            if (items[i].type.indexOf('image') !== -1) {
                const reader = new FileReader()
                reader.onload = function(event) {
                    setTimeout(() => {
                      const img = document.querySelector('img[src^="blob\:http"]')
                      if (img) {
                        img.src = event.target.result;
                        onInput();
                      }
                    }, 1);
                }
                reader.readAsDataURL(items[i].getAsFile());
                break;
            }
        }
      }
    });

    load();
  </script>
</body>
</html>